package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderPrincipalT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CCECDiagnoseRepairMsgTService;
import com.cci.kangdao.service.NoticeService;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//ccec诊断维修信息
@Service("CCECDiagnoseRepairMsgTService")
public class CCECDiagnoseRepairMsgTServiceImpl implements CCECDiagnoseRepairMsgTService {

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private WorkOrderTDao workOrderTDao;
	@Autowired
	private LoginDao loginDao;
	@Autowired
	private UserTDao userTDao;
	@Autowired
	private ServiceStationDao serviceStationDao;
	@Autowired
	private CompanyTDao companyTDao;
	@Autowired
	private CRMPlatformServiceDao platformServiceDao;
	@Autowired
	private WorkOrderPrincipalTDao workOrderPrincipalTDao;
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Resource
	private EngineMsgDao engineMsgDao;
	@Resource
	private NoticeService noticeService;
	@Resource
	private WorkOrderTServiceImpl workOrderTServiceImpl;
	@Resource
	private CCECDiagnoseRepairMsgTDao ccecDiagnoseRepairMsgTDao;
	@Resource
    private PartInfoTDao partInfoTDao;
	@Resource
	private CRMPlatformServiceDao crmServiceDao;
	@Resource
	private WorkOrderRepairDao workOrderRepairDao;

	//ccec技师开始诊断保存和提交确认报修信息
	@Transactional
	@Override
	public ModelAndView submitAffirmRepairsMsg(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			UserT userT = UserThreadLocal.get();
			int orderStatus = 26;	//提交完确认报修信息   工单状态变为诊断中
			String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
			//类型    1代表保存确认报修信息     2代表提交确认报修信息
			int type = MapUtils.getIntValue(map,"type",-1);
			if(type == -1){
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "类型不能为空，未知操作!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(!map.containsKey("orderId")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "工单id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(!map.containsKey("EngineIsMatching")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "发动机是否匹配不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			int engineIsMatching = MapUtils.getIntValue(map,"EngineIsMatching",1);   //发动机是否匹配(0否   1是)
			if(engineIsMatching == 0 && !map.containsKey("RealEngineMsgId")) {   //发动机是否匹配为否时  真实esn不能为空
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "实际发动机号不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(!map.containsKey("IsWarrantyDate")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "发动机是否起保不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			int isWarrantyDate = MapUtils.getIntValue(map,"IsWarrantyDate");   //发动机是否起保
			if(!map.containsKey("AffirmFaultSymptom")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "确认的故障症状不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			long orderId = MapUtils.getLongValue(map,"orderId");
			Map<String,Object> oldDiagnosiResultMap = ccecDiagnoseRepairMsgTDao.getDiagnosiResultMsgByOrderId(orderId);
			if(MapUtils.isNotEmpty(oldDiagnosiResultMap)){   //存在就更新
				map.put("ID",MapUtils.getLongValue(oldDiagnosiResultMap,"ID"));
                map.put("Updator",userT.getId());
                map.put("UpdateTime",currentTime);
				ccecDiagnoseRepairMsgTDao.updateByPrimaryKeySelective(map);
			}else{  //不存在新增
				map.put("OrderId",orderId);
				Map<String,Object> insertMap = new HashMap<>();
				insertMap.putAll(map);
				insertMap.put("Creator",userT.getId());
				insertMap.put("CreateTime",currentTime);
				ccecDiagnoseRepairMsgTDao.insertSelective(map);
			}
			WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
			Map<String,Object> currentWorkOrderEngineMap = engineMsgDao.getSMNByESN(workOrderT.getESN());
			String warrantyStartDate = MapUtils.getString(map,"WarrantyStartDate","");
			//如果前端传了图片或者起保日期，就更新起保日期和照片
			Map<String,Object> updateEngineMap = new HashMap<>();
			if(engineIsMatching == 0){
				updateEngineMap.put("id", MapUtils.getLongValue(map,"RealEngineMsgId"));
			}else{
				updateEngineMap.put("id", MapUtils.getLongValue(currentWorkOrderEngineMap,"id"));
			}
			String engineStartDatePicUrl = MapUtils.getString(map,"EngineStartDatePicUrl","");
			if(StringUtils.isNotEmpty(warrantyStartDate) || StringUtils.isNotEmpty(engineStartDatePicUrl)){
				updateEngineMap.put("warrantyStartDate",warrantyStartDate);
				updateEngineMap.put("EngineStartDatePicUrl",engineStartDatePicUrl );
				engineMsgDao.updateEngineMsg(updateEngineMap);
			}

			/*if(isWarrantyDate == 0) {  //发动机是否起保为否时  更新前端传的起保日期和照片到相应的发动机基础数据
				long realEngineMsgId = MapUtils.getLongValue(map,"RealEngineMsgId");
				if(StringUtils.isNotEmpty(warrantyStartDate) || StringUtils.isNotEmpty(engineStartDatePicUrl)){
					updateEngineMap.put("warrantyStartDate",warrantyStartDate);
					updateEngineMap.put("EngineStartDatePicUrl",engineStartDatePicUrl );
					updateEngineMap.put("id", realEngineMsgId);
					engineMsgDao.updateEngineMsg(updateEngineMap);
				}
			}else{   //发动机是否起保为是时   如果原本后台基础数据没有起保日期和照片时   前端也会拍照
				if(StringUtils.isNotEmpty(warrantyStartDate) || StringUtils.isNotEmpty(engineStartDatePicUrl)){
					updateEngineMap.put("warrantyStartDate",warrantyStartDate);
					updateEngineMap.put("EngineStartDatePicUrl", engineStartDatePicUrl);
					updateEngineMap.put("id", MapUtils.getLongValue(currentWorkOrderEngineMap,"id"));
					engineMsgDao.updateEngineMsg(updateEngineMap);
				}
			}*/
			if(type == 1){
				//没逻辑
			}else if(type == 2){     //2代表提交确认报修信息     除了以上更新保存确认报修信息还需要修改工单状态等
				map.put("ID",orderId);
				map.put("Updator",userT.getId());
				map.put("UpdateTime",currentTime);
				map.put("OrderStatus",orderStatus);
				map.put("RealESN",MapUtils.getString(map,"RealESN"));
				map.put("oldUpdateTime",MapUtils.getString(map,"oldUpdateTime",""));
				//更新工单信息
				int updateWorkOrderResult = workOrderTDao.updateByPrimaryKeySelective(map);
				if(updateWorkOrderResult == 0){
					obj.put("status", SMSEnum.type21.getIndex());
					obj.put("msg", SMSEnum.type21.getName());
					obj.put("data", "");
					//主动回滚事务
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
				String  locLon = MapUtils.getString (map,"locLon");
				String  locLat = MapUtils.getString (map,"locLat");
				String  location = MapUtils.getString (map,"location");
				String  IMEI = MapUtils.getString (map,"IMEI");
				//调用2.2.3 APP系统同步工单状态信息到CRM系统
				Map<String, Object> parameters1 = new HashMap<>();
				parameters1.put("orderNo",workOrderT.getOrderNo());
				parameters1.put("billStatus",orderStatus);
				parameters1.put("actionTime",currentTime);
				parameters1.put("directorName",userT.getContact());
				parameters1.put("directorPhone",userT.getPhone());
				parameters1.put("positionLat",locLat);
				parameters1.put("positionLon",locLon);
				parameters1.put("phoneIMEI",IMEI);
                parameters1.put("imei", IMEI);
				parameters1.put("location",location);
				parameters1.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
				parameters1.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
				parameters1.put("customerName",workOrderT.getCustomerName());
				parameters1.put("customerPhone",workOrderT.getCustomerPhone());
				parameters1.put("customerCompany",workOrderT.getCustomerCompanyName());
				parameters1.put("faultDesc",workOrderT.getCustomerComplaint());
				Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(workOrderT.getServiceStationId(),workOrderT.getOrderChannel());
				if(MapUtils.isNotEmpty(sSRepair)){
					parameters1.put("stationNo",sSRepair.get("BusinessNo"));
					parameters1.put("stationName",sSRepair.get("StationName"));
				}else{
					parameters1.put("stationNo","");
					parameters1.put("stationName","");
				}
				try {
					CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
					if(crmResponeEntity.getStatus() != 0) {
						log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
				}

				//调用2.2.14 APP系统同步工单报修确认信息到CCSS系统
				Map<String, Object> parameters2 = new HashMap<>();
				parameters2.put("orderNo",workOrderT.getOrderNo());
				parameters2.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
				parameters2.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
				parameters2.put("ESN",workOrderT.getESN());
				parameters2.put("isESNMatched",engineIsMatching);
				parameters2.put("realESN", MapUtils.getString(map,"RealESN",""));
				parameters2.put("isWarranty", MapUtils.getIntValue(map,"IsWarrantyDate"));
				parameters2.put("startDatePicUrl", MapUtils.getString(map,"EngineStartDatePicUrl",""));
				parameters2.put("faultSymptom", MapUtils.getString(map,"AffirmFaultSymptom",""));
				parameters2.put("warrantyStartDate",warrantyStartDate);
				parameters2.put("remark", MapUtils.getString(map,"RepairsMsgOrther",""));
				parameters2.put("type","");
				try {
					CRMApiUtils.getCRMServiceApi().syncWorkOrderAffirm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),parameters2);
				} catch (Exception e) {
					log.error("同步工单报修确认信息至CRM失败!错误信息:" + e.getMessage(),e);
				}

				//插入工单操作记录表
				workOrderTServiceImpl.saveOperation(workOrderT.getId(), userT.getId(), orderStatus, "CCEC服务技师提交确认报修信息", locLon, locLat, location, IMEI, 0, userT.getId(), currentTime);
				//保存消息提醒集合
				String customerMsgbody = "您的工单服务技师开始诊断，工单号"+workOrderT.getOrderNo()+"，请查看。";  //给客户推送短信app
				long customerId = workOrderT.getCustomerId();  //用户表主键id   客户在系统中时有值
				String customerPhone = workOrderT.getCustomerPhone(); //客户手机号
				UserT customerT = new UserT();
				if(-1 != customerId){
					customerT = loginDao.getUserByid(String.valueOf(customerId));
				}
				if(null == customerT){
					List<UserT> users = loginDao.getUserByPhone(customerPhone);
					if(CollectionUtils.isNotEmpty(users)){
						customerT = users.get(0);
					}
				}
				if(null == customerT){
					noticeService.sendSMS(6,1,orderId,0L,customerPhone,customerMsgbody,userT.getId());
					noticeService.push(6,1,orderId,0L,"","新工单提醒",customerMsgbody,customerMsgbody,userT.getId());
				}else{
					noticeService.sendSMS(6,1,orderId,customerT.getId(),customerPhone,customerMsgbody,userT.getId());
					noticeService.push(6,1,orderId,customerT.getId(),customerT.getUserName(),"新工单提醒",customerMsgbody,customerMsgbody,userT.getId());
				}
				String otherMsgbody = "";   //给服务商站长  信息员推送短信app
				if(StringUtils.isNotEmpty(workOrderT.getCCSSOrderNo())){
					otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单（FW号"+workOrderT.getCCSSOrderNo()+"）服务技师已开始诊断，请查看。";
				}else{
					otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单服务技师已开始诊断，请查看。";
				}
				List<UserT> serviceStationUserList = userTDao.getStationMasterListByServiceStationId(workOrderT.getServiceStationId());
				if(CollectionUtils.isNotEmpty(serviceStationUserList)){
					for(UserT serviceStationUser : serviceStationUserList){
						noticeService.sendSMS(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getPhone(),otherMsgbody,userT.getId());
						noticeService.push(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getUserName(),"新工单提醒",otherMsgbody,otherMsgbody,userT.getId());
					}
				}
				map.put("workOrderId",workOrderT.getId());
				List<WorkOrderPrincipalT> workOrderPrincipalTList =  workOrderPrincipalTDao.getWorkOrderPrincipalTListByOrderId(map);
				//插入负责人表   主副技师
				if(CollectionUtils.isNotEmpty(workOrderPrincipalTList)) {
					for(WorkOrderPrincipalT workOrderPrincipalT : workOrderPrincipalTList) {
						workOrderTServiceImpl.savePrincipal(workOrderT.getId(),orderStatus,workOrderPrincipalT.getIsPrincipal(),workOrderPrincipalT.getUserId(),userT.getId(),currentTime);
					}
				}
			}else{
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "未知操作!");
				//主动回滚事务
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


    //CCEC技师查询诊断维修详情
    @Transactional
    @Override
    public ModelAndView getDiagnosiResult(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");
        try{
            JSONObject obj = new JSONObject();  //声明返给前端json对象
            if(!map.containsKey("orderId")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "工单id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            long orderId = MapUtils.getLongValue(map,"orderId");
            Map<String,Object> workOrderMap = workOrderTDao.getOrderById(orderId);
            int orderStatus = MapUtils.getIntValue(workOrderMap,"OrderStatus");
            Map<String,Object> returnMap = new HashMap<>();  //返给前端的map
            returnMap.put("isHavediagnosiResultMsg",0);   //是否存在诊断维修详情(0否    1是)前端根据这个值判断拿不拿详情信息
            Map<String,Object> diagnosiResultMsgMap = ccecDiagnoseRepairMsgTDao.getDiagnosiResultByOrderId(orderId);
            if(MapUtils.isNotEmpty(diagnosiResultMsgMap)){
				returnMap.putAll(diagnosiResultMsgMap);
			}
            List<Integer> diagnosiResultMsgList = new ArrayList<>();
            if(MapUtils.isNotEmpty(diagnosiResultMsgMap)){
            	//拼接返给前端诊断维修信息关键字集合
				//确认的故障症状
				String affirmFaultSymptom = MapUtils.getString(diagnosiResultMsgMap,"AffirmFaultSymptom","");
				//诊断步骤及结果
				String diagnoseStepResult = MapUtils.getString(diagnosiResultMsgMap,"DiagnoseStepResult","");
				//故障排除的步骤及结果
				String faultExcludeStepResult = MapUtils.getString(diagnosiResultMsgMap,"FaultExcludeStepResult","");
				if(StringUtils.isNotEmpty(affirmFaultSymptom) && (orderStatus == 12 || orderStatus == 13 || orderStatus == 14 || orderStatus >= 26)){
					diagnosiResultMsgList.add(1);
				}
				if(StringUtils.isNotEmpty(diagnoseStepResult) && (orderStatus == 12 || orderStatus == 13 || orderStatus == 14 || orderStatus >= 27)){
					diagnosiResultMsgList.add(2);
				}
				if(StringUtils.isNotEmpty(faultExcludeStepResult)){
					diagnosiResultMsgList.add(3);
				}
            	//拼接零件逻辑
                String partInfo = MapUtils.getString(diagnosiResultMsgMap,"PartInfo","");
				String faultCodeInfo = MapUtils.getString(diagnosiResultMsgMap,"FaultCodeInfos","");
                List<Map<String,Object>> partInfoTS = new ArrayList<>();
                if(StringUtils.isNotEmpty(partInfo)){  //零件信息不为空
                    String[] partInfoIds = partInfo.split(",");
					Map<String,Object> partInfoTMap = new HashMap<>();
					for(String partInfoId : partInfoIds){
						partInfoTMap = partInfoTDao.getPartInfoTById(Long.parseLong(partInfoId));
                        partInfoTS.add(partInfoTMap);
                    }
					if(CollectionUtils.isNotEmpty(partInfoTS) && StringUtils.isNotEmpty(faultCodeInfo)){
						String[] faultCodeInfos = faultCodeInfo.split(",");
						int index = 0;
						if(faultCodeInfos.length != 0){
							for(Map<String,Object> partInfoMap : partInfoTS){
								if(index < faultCodeInfos.length ) {
									if (StringUtils.isNotEmpty(faultCodeInfos[index])) {
										partInfoMap.put("FaultCode", faultCodeInfos[index]);
									} else {
										partInfoMap.put("FaultCode", "");
									}
										index++;
									}else{
										partInfoMap.put("FaultCode", "");
									}
								}
							}else{
								for(Map<String,Object> partInfoMap : partInfoTS){
									partInfoMap.put("FaultCode","");
								}
							}
						}
					}
                returnMap.put("partInfoTS",partInfoTS);
                if(StringUtils.isNotEmpty(MapUtils.getString(diagnosiResultMsgMap,"CCECDiagnoseRepairMsId",""))){
					returnMap.put("isHavediagnosiResultMsg",1);
				}
            }
			returnMap.put("diagnosiResultMsgList",diagnosiResultMsgList);
            obj.put("data", returnMap);
            obj.put("status", 0);
            obj.put("msg", "success");
            ParameterTool.writeResponse(response, obj.toString());
        } catch(Exception e) {
            ParameterTool.writeErrorResponse(response);
            //主动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage(),e);
        }
        return null;
    }


	//CCEC技师修改  新增诊断结果
	@Transactional
	@Override
	public ModelAndView operationDiagnosiResult(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			UserT userT = UserThreadLocal.get();
            String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
			//类型    1代表保存诊断结果     2代表提交诊断结果
			int type = MapUtils.getIntValue(map,"type",-1);
			if(type == -1){
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "类型不能为空，未知操作!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(!map.containsKey("orderId")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "工单id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			//不管是保存还是提交诊断结果    都判断是否存在之前的诊断结果    有就更新    没有就新增
			long orderId = MapUtils.getLongValue(map,"orderId");
            Map<String,Object> oldDiagnosiResultMap = ccecDiagnoseRepairMsgTDao.getDiagnosiResultMsgByOrderId(orderId);
            if(MapUtils.isNotEmpty(oldDiagnosiResultMap)){   //存在就更新
                map.put("ID",MapUtils.getLongValue(oldDiagnosiResultMap,"ID"));
                map.put("Updator",userT.getId());
                map.put("UpdateTime",currentTime);
                ccecDiagnoseRepairMsgTDao.updateByPrimaryKeySelective(map);
            }else{  //不存在新增
            	Map<String,Object> insertMap = new HashMap<>();
				insertMap.putAll(map);
				insertMap.put("Creator",userT.getId());
				insertMap.put("CreateTime",currentTime);
                ccecDiagnoseRepairMsgTDao.insertSelective(insertMap);
            }
            if(type == 1){
                //没逻辑
            }else if(type == 2){  //2代表提交诊断结果     除了以上更新保存诊断结果还需要修改工单状态等
                int isBeginRepair = MapUtils.getIntValue(map, "IsBeginRepair", -1);  //是否可以开始维修
				WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
				String  locLon = MapUtils.getString (map,"locLon");
				String  locLat = MapUtils.getString (map,"locLat");
				String  location = MapUtils.getString (map,"location");
				String  IMEI = MapUtils.getString (map,"IMEI");
				if(isBeginRepair == 1){   //可以开始维修
					int orderStatus = 27;	  //提交诊断结果      工单状态变为诊断完成
					map.put("ID",orderId);
					map.put("Updator",userT.getId());
					map.put("UpdateTime",currentTime);
					map.put("OrderStatus",orderStatus);
					map.put("oldUpdateTime",MapUtils.getString(map,"oldUpdateTime",""));
					//更新工单信息
					int updateWorkOrderResult = workOrderTDao.updateByPrimaryKeySelective(map);
					if(updateWorkOrderResult == 0){
						obj.put("status", SMSEnum.type21.getIndex());
						obj.put("msg", SMSEnum.type21.getName());
						obj.put("data", "");
						//主动回滚事务
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						//返回客户
						ParameterTool.writeResponse(response, obj.toString());
						return null;
					}
					//调用2.2.3 APP系统同步工单状态信息到CRM系统
					Map<String, Object> parameters1 = new HashMap<>();
					parameters1.put("orderNo",workOrderT.getOrderNo());
					parameters1.put("billStatus",orderStatus);
					parameters1.put("actionTime",currentTime);
					parameters1.put("directorName",userT.getContact());
					parameters1.put("directorPhone",userT.getPhone());
					parameters1.put("positionLat",locLat);
					parameters1.put("positionLon",locLon);
					parameters1.put("phoneIMEI",IMEI);
                    parameters1.put("imei", IMEI);
					parameters1.put("location",location);
					parameters1.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
					parameters1.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
					parameters1.put("customerName",workOrderT.getCustomerName());
					parameters1.put("customerPhone",workOrderT.getCustomerPhone());
					parameters1.put("customerCompany",workOrderT.getCustomerCompanyName());
					parameters1.put("faultDesc",workOrderT.getCustomerComplaint());
					Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(workOrderT.getServiceStationId(),workOrderT.getOrderChannel());
					if(MapUtils.isNotEmpty(sSRepair)){
						parameters1.put("stationNo",sSRepair.get("BusinessNo"));
						parameters1.put("stationName",sSRepair.get("StationName"));
					}else{
						parameters1.put("stationNo","");
						parameters1.put("stationName","");
					}
					try {
						CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
						if(crmResponeEntity.getStatus() != 0) {
							log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}

					//2.2.16 APP系统同步诊断结果确认信息到CCSS系统
					Map<String, Object> parameters2 = new HashMap<>();
					parameters2.put("orderNo",workOrderT.getOrderNo());
					parameters2.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
					parameters2.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
					parameters2.put("faultSymptom",MapUtils.getString(map,"AffirmFaultSymptom",""));
					parameters2.put("diagnosisStepsAndResults",MapUtils.getString(map,"DiagnoseStepResult",""));
					parameters2.put("insureResponsibility",MapUtils.getString(map,"ConfirmDutyValue",""));
					parameters2.put("isStartRepair",MapUtils.getIntValue(map,"IsBeginRepair"));
					//拼装传给crm的零件集合
					List<Map<String,Object>> partInfoTS = new ArrayList<>();
					String partInfo = MapUtils.getString(map,"PartInfo","");
					String faultCodeInfo = MapUtils.getString(map,"FaultCodeInfos","");
					if(StringUtils.isNotEmpty(partInfo)){  //零件信息不为空
						String[] partInfoIds = partInfo.split(",");
						Map<String,Object> partInfoTMap = new HashMap<>();
						for(String partInfoId : partInfoIds){
							partInfoTMap = partInfoTDao.getPartInfoTById(Long.parseLong(partInfoId));
							if(MapUtils.isNotEmpty(partInfoTMap)){
								partInfoTMap.put("partNo",MapUtils.getString(partInfoTMap,"PartNumber",""));
								partInfoTMap.put("partName",MapUtils.getString(partInfoTMap,"PartName",""));
								partInfoTS.add(partInfoTMap);
							}

						}
						if(CollectionUtils.isNotEmpty(partInfoTS)){
							if(StringUtils.isNotEmpty(faultCodeInfo)){
								String[] faultCodeInfos = faultCodeInfo.split(",");
								int index = 0;
								for(Map<String,Object> partInfoMap : partInfoTS){
									if(index < faultCodeInfos.length){
										if(StringUtils.isNotEmpty(faultCodeInfos[index])){
											partInfoMap.put("faultCode",faultCodeInfos[index]);
										}else{
											partInfoMap.put("faultCode","");
										}
										index++;
									}else{
										partInfoMap.put("faultCode","");
									}
								}
							}else{
								for(Map<String,Object> partInfoMap : partInfoTS){
									partInfoMap.put("faultCode","");
								}
							}
						}
					}
					parameters2.put("partsList",partInfoTS);
					try {
						CRMApiUtils.getCRMServiceApi().syncConfirmationRepair(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),parameters2);
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单诊断结果信息至CRM失败!错误信息:" + e.getMessage(),e);
					}

					//插入工单操作记录表
					workOrderTServiceImpl.saveOperation(workOrderT.getId(), userT.getId(), orderStatus, "CCEC服务技师提交诊断结果信息", locLon, locLat, location, IMEI, 0, userT.getId(), currentTime);
					//保存消息提醒集合
					String otherMsgbody = "";   //给服务商站长  信息员推送短信app
					if(StringUtils.isNotEmpty(workOrderT.getCCSSOrderNo())){
						otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单（FW号"+workOrderT.getCCSSOrderNo()+"）服务技师已诊断完成，请查看。";
					}else{
						otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单服务技师已诊断完成，请查看。";
					}
					List<UserT> serviceStationUserList = userTDao.getStationMasterListByServiceStationId(workOrderT.getServiceStationId());
					if(CollectionUtils.isNotEmpty(serviceStationUserList)){
						for(UserT serviceStationUser : serviceStationUserList){
							noticeService.sendSMS(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getPhone(),otherMsgbody,userT.getId());
							noticeService.push(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getUserName(),"新工单提醒",otherMsgbody,otherMsgbody,userT.getId());
						}
					}
					map.put("workOrderId",orderId);
					List<WorkOrderPrincipalT> workOrderPrincipalTList =  workOrderPrincipalTDao.getWorkOrderPrincipalTListByOrderId(map);
					//插入负责人表   主副技师
					if(CollectionUtils.isNotEmpty(workOrderPrincipalTList)) {
						for(WorkOrderPrincipalT workOrderPrincipalT : workOrderPrincipalTList) {
							workOrderTServiceImpl.savePrincipal(workOrderT.getId(),orderStatus,workOrderPrincipalT.getIsPrincipal(),workOrderPrincipalT.getUserId(),userT.getId(),currentTime);
						}
					}
				}else{   //不可以开始维修
                    int orderStatus = 31;      //工单状态变为异常关闭申请中    2.7.0ccec需求变动
					map.put("ID",orderId);
					map.put("Updator",userT.getId());
					map.put("UpdateTime",currentTime);
					map.put("OrderStatus",orderStatus);
					//更新工单信息
					int updateWorkOrderResult = workOrderTDao.updateByPrimaryKeySelective(map);
					if(updateWorkOrderResult == 0){
						obj.put("status", SMSEnum.type21.getIndex());
						obj.put("msg", SMSEnum.type21.getName());
						obj.put("data", "");
						//主动回滚事务
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						//返回客户
						ParameterTool.writeResponse(response, obj.toString());
						return null;
					}
					//插入工单操作记录表
                    workOrderTServiceImpl.saveOperation(workOrderT.getId(), userT.getId(), orderStatus, "CCEC服务技师提交诊断结果信息并且选择不能开始维修，工单异常关闭状态变为异常关闭申请中", locLon, locLat, location, IMEI, 0, userT.getId(), currentTime);
                    //保存消息提醒集合
                    String otherMsgbody = "";   //给服务商站长  信息员推送,ccec400短信app
                    if (StringUtils.isNotEmpty(workOrderT.getCCSSOrderNo())) {
                        otherMsgbody = "您有工单申请异常关闭，工单号" + workOrderT.getOrderNo() + "（FW号" + workOrderT.getCCSSOrderNo() + "），请查看。";
                    } else {
                        otherMsgbody = "您有工单申请异常关闭，工单号" + workOrderT.getOrderNo() + "，请查看。";
                    }
                    List<UserT> serviceStationUserList = userTDao.getStationMasterListByServiceStationId(workOrderT.getServiceStationId());
                    if (CollectionUtils.isNotEmpty(serviceStationUserList)) {
                        for (UserT serviceStationUser : serviceStationUserList) {
                            noticeService.sendSMS(6, 1, orderId, serviceStationUser.getId(), serviceStationUser.getPhone(), otherMsgbody, userT.getId());
                            noticeService.push(6, 1, orderId, serviceStationUser.getId(), serviceStationUser.getUserName(), "新工单提醒", otherMsgbody, otherMsgbody, userT.getId());
                        }
                    }
                    map.put("ServiceStationId", workOrderT.getServiceStationId());
                    map.put("OrderChannel", workOrderT.getOrderChannel());
                    List<Map<String, Object>> areaManagerMapList = workOrderRepairDao.getAreaManager(map);
                    if (CollectionUtils.isNotEmpty(areaManagerMapList)) {
                        for (Map<String, Object> areaManagerMap : areaManagerMapList) {
                            //插入负责人表
                            workOrderTServiceImpl.savePrincipal(workOrderT.getId(), orderStatus, 1, MapUtils.getLongValue(areaManagerMap, "ID"), userT.getId(), currentTime);
                            //给ccec400推送短信
                            noticeService.sendSMS(6, 1, orderId, MapUtils.getLongValue(areaManagerMap, "ID"), MapUtils.getString(areaManagerMap, "phone"), otherMsgbody, userT.getId());
                            noticeService.push(6, 1, orderId, MapUtils.getLongValue(areaManagerMap, "ID"), MapUtils.getString(areaManagerMap, "UserName"), "新工单提醒", otherMsgbody, otherMsgbody, userT.getId());
                        }
                    }


					//生成新工单   工单状态为24    待400审核	400回访/诊断中/继续服务/待更新
					/*int newOrderStatus = 24;
					Map<String,Object> oldWorkOrderMap = workOrderTDao.getCCECOldWorkOrderMsgById(orderId);
					oldWorkOrderMap.put("createUserId",userT.getId());
					Map<String,Object> newWorkOrderMap = workOrderTServiceImpl.createNewWorkOrder(oldWorkOrderMap,newOrderStatus);
					String newOrderNo = "";
					if(MapUtils.isNotEmpty(newWorkOrderMap)){
						long newWorkOrderId = MapUtils.getLongValue(newWorkOrderMap,"OrderId");
						// 旧工单关联新工单表id
						newWorkOrderMap.put("newOrderId",newWorkOrderId);
						newWorkOrderMap.put("RelOrderId",newWorkOrderId);
						newWorkOrderMap.put("oldOrderId",workOrderT.getId());
						crmServiceDao.updateRelOrderId(newWorkOrderMap);
						newOrderNo = MapUtils.getString(newWorkOrderMap,"OrderNo");
						//保存工单操作记录表
						workOrderTServiceImpl.saveOperation(newWorkOrderId, userT.getId(), newOrderStatus, "CCEC服务技师提交诊断结果信息并且选择不能开始维修，生成新工单，待400审核", locLon, locLat, location, IMEI, 0, userT.getId(), currentTime);
						//推送短信和app消息
						String newMsgbody = "您有工单待审核，工单号"+newOrderNo+"，请尽快处理。";
						//获取ccec所有的400
						List<Map<String,Object>> areaManagerMapList = workOrderRepairDao.getCCECAreaManager(workOrderT.getOrderChannel());
						List<Map<String,Object>> notifyRecordTMapList = new ArrayList<>();
						if(CollectionUtils.isNotEmpty(areaManagerMapList)) {
							for(Map<String,Object> areaManagerMap : areaManagerMapList){
								long  receiverId = MapUtils.getLongValue(areaManagerMap,"ID");
								String receiverUserName = MapUtils.getString(areaManagerMap,"UserName");
								//保存负责人
								workOrderTServiceImpl.savePrincipal(newWorkOrderId,newOrderStatus,1,receiverId,userT.getId(),currentTime);
								//推送app提醒并入库
								noticeService.push(2,1,newWorkOrderId,receiverId,receiverUserName,"新工单提醒",newMsgbody,newMsgbody,userT.getId());
								SmsTool.sendSms(userT.getPhone(), newMsgbody);  //推送短信
								//放进集合中   下面入库
								notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(newWorkOrderId,2,1,receiverId,newMsgbody,1,currentTime,"",userT.getId()));
							}
							if(CollectionUtils.isNotEmpty(notifyRecordTMapList)){
								workOrderRepairDao.saveMsgOperation(notifyRecordTMapList);
							}
						}
					}*/
                    //调用2.2.3 APP系统同步工单状态信息到CRM系统
					Map<String, Object> parameters1 = new HashMap<>();
					parameters1.put("orderNo",workOrderT.getOrderNo());
                    parameters1.put("CCSSComplainerOrderNo", workOrderT.getOrderNoCrm());
                    parameters1.put("CCSSOrderNo", workOrderT.getCCSSOrderNo());
					parameters1.put("billStatus",orderStatus);
                    parameters1.put("customerName", workOrderT.getCustomerName());
                    parameters1.put("customerPhone", workOrderT.getCustomerPhone());
                    parameters1.put("customerCompany", workOrderT.getCustomerCompanyName());
                    parameters1.put("faultDesc", workOrderT.getCustomerComplaint());
					parameters1.put("actionTime",currentTime);
					parameters1.put("directorName",userT.getContact());
					parameters1.put("directorPhone",userT.getPhone());
					parameters1.put("positionLat",locLat);
					parameters1.put("positionLon",locLon);
					parameters1.put("phoneIMEI",IMEI);
                    parameters1.put("imei", IMEI);
					parameters1.put("location",location);
					try {
						CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
						if(crmResponeEntity.getStatus() != 0) {
							log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}
					//调用2.2.3 APP系统同步新工单状态信息到CRM系统
					/*Map<String, Object> parameters2 = new HashMap<>();
					parameters2.put("orderNo",newOrderNo);
					parameters2.put("billStatus",newOrderStatus);
					parameters2.put("actionTime",currentTime);
					parameters2.put("directorName",userT.getContact());
					parameters2.put("directorPhone",userT.getPhone());
					parameters2.put("positionLat",locLat);
					parameters2.put("positionLon",locLon);
					parameters2.put("phoneIMEI",IMEI);
                    parameters1.put("imei", IMEI);
					parameters2.put("location",location);
					parameters2.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
					parameters2.put("CCSSOrderNo","");
					parameters2.put("customerName",workOrderT.getCustomerName());
					parameters2.put("customerPhone",workOrderT.getCustomerPhone());
					parameters2.put("customerCompany",workOrderT.getCustomerCompanyName());
					parameters2.put("faultDesc",workOrderT.getCustomerComplaint());
					try {
						CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),platformServiceDao,redisClientUtils,parameters2);
						if(crmResponeEntity.getStatus() != 0) {
							log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}*/
				}
			}else{
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "未知操作!");
				//主动回滚事务
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//CCEC技师诊断维修   输入零件号  校验是否存在   存在返回零件相关信息
	@Transactional
	@Override
	public ModelAndView checkoutPartInfo(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			if(!map.containsKey("PartNumber")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "零件号不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			String partNumber = MapUtils.getString(map,"PartNumber");
			Map<String,Object> partInfoMap = partInfoTDao.getPartInfoTByPartNumber(partNumber);
			Map<String,Object> returnMap = new HashMap<>();
			if(MapUtils.isNotEmpty(partInfoMap)){
				returnMap.put("PartInfo",partInfoMap);
				obj.put("data", returnMap);
				obj.put("status", 0);
				obj.put("msg", "success");
			}else{
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "该零件号不存在，请拨打重庆康明斯热线电话");
			}
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//CCEC技师开始维修
	@Override
	public ModelAndView startRepairFoCCEC(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			if(!map.containsKey("orderId")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "工单id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			UserT userT = UserThreadLocal.get();
			int orderStatus = 12;	//点击开始维修   工单状态变为   	维修中
			String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
			long orderId = MapUtils.getLongValue(map,"orderId");
			map.put("ID",orderId);
			map.put("Updator",userT.getId());
			map.put("UpdateTime",currentTime);
			map.put("OrderStatus",orderStatus);
			map.put("oldUpdateTime",MapUtils.getString(map,"oldUpdateTime",""));
			//更新工单信息
			int updateWorkOrderResult = workOrderTDao.updateByPrimaryKeySelective(map);
			if(updateWorkOrderResult == 0){
				obj.put("status", SMSEnum.type21.getIndex());
				obj.put("msg", SMSEnum.type21.getName());
				obj.put("data", "");
				//主动回滚事务
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
			String  locLon = MapUtils.getString (map,"locLon");
			String  locLat = MapUtils.getString (map,"locLat");
			String  location = MapUtils.getString (map,"location");
			String  IMEI = MapUtils.getString (map,"IMEI");
			//调用2.2.3 APP系统同步工单状态信息到CRM系统
			Map<String, Object> parameters1 = new HashMap<>();
			parameters1.put("orderNo",workOrderT.getOrderNo());
			parameters1.put("billStatus",orderStatus);
			parameters1.put("actionTime",currentTime);
			parameters1.put("directorName",userT.getContact());
			parameters1.put("directorPhone",userT.getPhone());
			parameters1.put("positionLat",locLat);
			parameters1.put("positionLon",locLon);
			parameters1.put("phoneIMEI",IMEI);
            parameters1.put("imei", IMEI);
			parameters1.put("location",location);
			parameters1.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
			parameters1.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
			parameters1.put("customerName",workOrderT.getCustomerName());
			parameters1.put("customerPhone",workOrderT.getCustomerPhone());
			parameters1.put("customerCompany",workOrderT.getCustomerCompanyName());
			parameters1.put("faultDesc",workOrderT.getCustomerComplaint());
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(workOrderT.getServiceStationId(),workOrderT.getOrderChannel());
			if(MapUtils.isNotEmpty(sSRepair)){
				parameters1.put("stationNo",sSRepair.get("BusinessNo"));
				parameters1.put("stationName",sSRepair.get("StationName"));
			}else{
				parameters1.put("stationNo","");
				parameters1.put("stationName","");
			}
			try {
				CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
				if(crmResponeEntity.getStatus() != 0) {
					log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
			}
			//插入工单操作记录表
			workOrderTServiceImpl.saveOperation(workOrderT.getId(), userT.getId(), orderStatus, "CCEC服务技师点击开始维修", locLon, locLat, location, IMEI, 0, userT.getId(), currentTime);
			String otherMsgbody = "";   //给服务商站长  信息员推送短信app
			if(StringUtils.isNotEmpty(workOrderT.getCCSSOrderNo())){
				otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单（FW号"+workOrderT.getCCSSOrderNo()+"），服务技师已开始维修，请查看。";
			}else{
				otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单服务技师已开始维修，请查看。";
			}
			List<UserT> serviceStationUserList = userTDao.getStationMasterListByServiceStationId(workOrderT.getServiceStationId());
			if(CollectionUtils.isNotEmpty(serviceStationUserList)){
				for(UserT serviceStationUser : serviceStationUserList){
					noticeService.sendSMS(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getPhone(),otherMsgbody,userT.getId());
					noticeService.push(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getUserName(),"新工单提醒",otherMsgbody,otherMsgbody,userT.getId());
				}
			}
			map.put("workOrderId",orderId);
			List<WorkOrderPrincipalT> workOrderPrincipalTList =  workOrderPrincipalTDao.getWorkOrderPrincipalTListByOrderId(map);
			//插入负责人表   主副技师
			if(CollectionUtils.isNotEmpty(workOrderPrincipalTList)) {
				for(WorkOrderPrincipalT workOrderPrincipalT : workOrderPrincipalTList) {
					workOrderTServiceImpl.savePrincipal(workOrderT.getId(),orderStatus,workOrderPrincipalT.getIsPrincipal(),workOrderPrincipalT.getUserId(),userT.getId(),currentTime);
				}
			}
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//ccec技师提交故障排查总结信息
	@Override
	public ModelAndView submitFaultExcludeStepResult(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			UserT userT = UserThreadLocal.get();
			int orderStatus = 13;	//提交完故障排查信息   	待用户评价
			String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
			if(!map.containsKey("orderId")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "工单id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(!map.containsKey("FaultExcludeStepResult")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "故障排查信息不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			long orderId = MapUtils.getLongValue(map,"orderId");
			map.put("ID",orderId);
			map.put("Updator",userT.getId());
			map.put("UpdateTime",currentTime);
			map.put("OrderStatus",orderStatus);
			map.put("oldUpdateTime",MapUtils.getString(map,"oldUpdateTime",""));
			//更新工单信息
			int updateWorkOrderResult = workOrderTDao.updateByPrimaryKeySelective(map);
			if(updateWorkOrderResult == 0){
				obj.put("status", SMSEnum.type21.getIndex());
				obj.put("msg", SMSEnum.type21.getName());
				obj.put("data", "");
				//主动回滚事务
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			Map<String,Object> oldDiagnosiResultMap = ccecDiagnoseRepairMsgTDao.getDiagnosiResultMsgByOrderId(orderId);
			if(MapUtils.isNotEmpty(oldDiagnosiResultMap)){   //存在就更新
				map.put("ID",MapUtils.getLongValue(oldDiagnosiResultMap,"ID"));
                map.put("Updator",userT.getId());
                map.put("UpdateTime",currentTime);
				ccecDiagnoseRepairMsgTDao.updateByPrimaryKeySelective(map);
			}
			WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
			String  locLon = MapUtils.getString (map,"locLon");
			String  locLat = MapUtils.getString (map,"locLat");
			String  location = MapUtils.getString (map,"location");
			String  IMEI = MapUtils.getString (map,"IMEI");
			//调用2.2.3 APP系统同步工单状态信息到CRM系统
			Map<String, Object> parameters1 = new HashMap<>();
			parameters1.put("orderNo",workOrderT.getOrderNo());
			parameters1.put("billStatus",orderStatus);
			parameters1.put("actionTime",currentTime);
			parameters1.put("directorName",userT.getContact());
			parameters1.put("directorPhone",userT.getPhone());
			parameters1.put("positionLat",locLat);
			parameters1.put("positionLon",locLon);
			parameters1.put("phoneIMEI",IMEI);
            parameters1.put("imei", IMEI);
			parameters1.put("location",location);
			parameters1.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
			parameters1.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
			parameters1.put("customerName",workOrderT.getCustomerName());
			parameters1.put("customerPhone",workOrderT.getCustomerPhone());
			parameters1.put("customerCompany",workOrderT.getCustomerCompanyName());
			parameters1.put("faultDesc",workOrderT.getCustomerComplaint());
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(workOrderT.getServiceStationId(),workOrderT.getOrderChannel());
			if(MapUtils.isNotEmpty(sSRepair)){
				parameters1.put("stationNo",sSRepair.get("BusinessNo"));
				parameters1.put("stationName",sSRepair.get("StationName"));
			}else{
				parameters1.put("stationNo","");
				parameters1.put("stationName","");
			}
			try {
				CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
				if(crmResponeEntity.getStatus() != 0) {
					log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
			}

			//调用2.2.13 APP系统同步故障排查总结信息到CCSS系统
			Map<String, Object> parameters2 = new HashMap<>();
			parameters2.put("orderNo",StringUtils.isEmpty(workOrderT.getOrderNo())?"":workOrderT.getOrderNo());
			parameters2.put("CCSSComplainerOrderNo",StringUtils.isEmpty(workOrderT.getOrderNoCrm())?"":workOrderT.getOrderNoCrm());
			parameters2.put("CCSSOrderNo",StringUtils.isEmpty(workOrderT.getCCSSOrderNo())?"":workOrderT.getCCSSOrderNo());
			parameters2.put("diagnosisStepsAndResults",MapUtils.getString(map,"DiagnoseStepResult",""));
			parameters2.put("defaultEliminateDes",MapUtils.getString(map,"FaultExcludeStepResult",""));
			try {
				CRMApiUtils.getCRMServiceApi().syncTroubleshootingSummary(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),parameters2);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("同步工单故障排除信息至CRM失败!错误信息:" + e.getMessage(),e);
			}

			//插入工单操作记录表
			workOrderTServiceImpl.saveOperation(workOrderT.getId(), userT.getId(), orderStatus, "CCEC服务技师提交故障排除信息", locLon, locLat, location, IMEI, 0, userT.getId(), currentTime);
			//保存消息提醒集合
			String customerMsgbody = "您的工单服务技师已维修完成，工单号"+workOrderT.getOrderNo()+"，请评价。";  //给客户推送短信app
			long customerId = workOrderT.getCustomerId();  //用户表主键id   客户在系统中时有值
			String customerPhone = workOrderT.getCustomerPhone(); //客户手机号
			UserT customerT = loginDao.getUserByid(String.valueOf(customerId));
			if(null == customerT){
				List<UserT> users = loginDao.getUserByPhone(customerPhone);
				if(CollectionUtils.isNotEmpty(users)){
					customerT = users.get(0);
				}
			}
			if(null == customerT){
				noticeService.sendSMS(6,1,orderId,0L,customerPhone,customerMsgbody,userT.getId());
				noticeService.push(6,1,orderId,0L,"","新工单提醒",customerMsgbody,customerMsgbody,userT.getId());
			}else{
				noticeService.sendSMS(6,1,orderId,customerT.getId(),customerPhone,customerMsgbody,userT.getId());
				noticeService.push(6,1,orderId,customerT.getId(),customerT.getUserName(),"新工单提醒",customerMsgbody,customerMsgbody,userT.getId());
			}
			String otherMsgbody = "";   //给服务商站长  信息员推送短信app
			if(StringUtils.isNotEmpty(workOrderT.getCCSSOrderNo())){
				otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单（FW号"+workOrderT.getCCSSOrderNo()+"）服务技师已维修完毕，请查看。";
			}else{
				otherMsgbody = "您的"+workOrderT.getOrderNo()+"号工单服务技师已维修完毕，请查看。";
			}
			List<UserT> serviceStationUserList = userTDao.getStationMasterListByServiceStationId(workOrderT.getServiceStationId());
			if(CollectionUtils.isNotEmpty(serviceStationUserList)){
				for(UserT serviceStationUser : serviceStationUserList){
					noticeService.sendSMS(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getPhone(),otherMsgbody,userT.getId());
					noticeService.push(6,1,orderId,serviceStationUser.getId(),serviceStationUser.getUserName(),"新工单提醒",otherMsgbody,otherMsgbody,userT.getId());
				}
			}
			//插入负责人表   用户
			workOrderTServiceImpl.savePrincipal(workOrderT.getId(),orderStatus,1,workOrderT.getCustomerId(),userT.getId(),currentTime);

			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//ccec技师修改确认报修信息，诊断结果信息和故障排查信息接口
    @Override
    public ModelAndView updateCCECDiagnoseRepairMsg(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");
        JSONObject obj = new JSONObject();  //声明返给前端json对象
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
        try{
            if(!map.containsKey("CCECDiagnoseRepairMsId")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "诊断维修信息id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            if(!map.containsKey("OrderId")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "工单id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }

            long orderId = MapUtils.getLongValue(map,"OrderId");
            WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
            //类型  用来区分前端是修改确认报修信息(1)，诊断结果信息(2)还是故障排查信息(3)
            int type = MapUtils.getIntValue(map,"Type",0);
            if(type == 0){
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "类型不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            Map<String, Object> parameters2 = new HashMap<>();
            parameters2.put("orderNo",workOrderT.getOrderNo());
            parameters2.put("CCSSComplainerOrderNo",workOrderT.getOrderNoCrm());
            parameters2.put("CCSSOrderNo",workOrderT.getCCSSOrderNo());
            if(type == 1){   //确认报修信息
                if(!map.containsKey("EngineIsMatching")) {
                    obj.put("data", "");
                    obj.put("status", 1);
                    obj.put("msg", "发动机是否匹配不能为空!");
                    ParameterTool.writeResponse(response, obj.toString());
                    return null;
                }
                int engineIsMatching = MapUtils.getIntValue(map,"EngineIsMatching",1);   //发动机是否匹配(0否   1是)
                if(engineIsMatching == 0 && !map.containsKey("RealEngineMsgId")) {   //发动机是否匹配为否时  真实esn不能为空
                    obj.put("data", "");
                    obj.put("status", 1);
                    obj.put("msg", "实际发动机号不能为空!");
                    ParameterTool.writeResponse(response, obj.toString());
                    return null;
                }
                if(!map.containsKey("IsWarrantyDate")) {
                    obj.put("data", "");
                    obj.put("status", 1);
                    obj.put("msg", "是否保修期内不能为空!");
                    ParameterTool.writeResponse(response, obj.toString());
                    return null;
                }
                if(!map.containsKey("AffirmFaultSymptom")) {
                    obj.put("data", "");
                    obj.put("status", 1);
                    obj.put("msg", "确认的故障症状不能为空!");
                    ParameterTool.writeResponse(response, obj.toString());
                    return null;
                }
                Map<String,Object> currentWorkOrderEngineMap = engineMsgDao.getSMNByESN(workOrderT.getESN());
                String warrantyStartDate = MapUtils.getString(map,"WarrantyStartDate","");
                String RealESN = MapUtils.getString(map,"RealESN","");
                //如果起保日期不为空，更新起保日期和照片
                Map<String,Object> updateEngineMap = new HashMap<>();
                WorkOrderT workOrderT1 = new WorkOrderT();
                if(engineIsMatching == 0) {  //不匹配   更新前端传的起保日期和照片到相应的发动机基础数据
                    long realEngineMsgId = MapUtils.getLongValue(map,"RealEngineMsgId");
                    if(StringUtils.isNotEmpty(warrantyStartDate)){
                        updateEngineMap.put("warrantyStartDate",warrantyStartDate);
                        updateEngineMap.put("EngineStartDatePicUrl", MapUtils.getString(map,"EngineStartDatePicUrl",""));
                        updateEngineMap.put("id", realEngineMsgId);
//                        updateEngineMap.put("ESN", RealESN);
                        engineMsgDao.updateEngineMsg(updateEngineMap);
                    }
					workOrderT1.setRealESN(RealESN);
					workOrderT1.setId(MapUtils.getLongValue(map,"OrderId",0L));
					workOrderTDao.updatRealESNById(workOrderT1);
                }else{   //匹配   如果原本后台基础数据没有起保日期和照片时   前端也会拍照
                    if(StringUtils.isNotEmpty(warrantyStartDate)){
                        updateEngineMap.put("warrantyStartDate",warrantyStartDate);
                        updateEngineMap.put("EngineStartDatePicUrl", MapUtils.getString(map,"EngineStartDatePicUrl",""));
                        updateEngineMap.put("id", MapUtils.getLongValue(currentWorkOrderEngineMap,"id"));
//						updateEngineMap.put("ESN", RealESN);
                        engineMsgDao.updateEngineMsg(updateEngineMap);
                    }
                }
                //调用2.2.14 APP系统同步工单报修确认信息到CCSS系统
                parameters2.put("ESN",workOrderT.getESN());
                parameters2.put("isESNMatched",engineIsMatching);
                parameters2.put("realESN", MapUtils.getString(map,"RealESN",""));
                parameters2.put("isWarranty", MapUtils.getIntValue(map,"IsWarrantyDate"));
                parameters2.put("startDatePicUrl", MapUtils.getString(map,"EngineStartDatePicUrl",""));
                parameters2.put("faultSymptom", MapUtils.getString(map,"AffirmFaultSymptom",""));
                parameters2.put("warrantyStartDate",warrantyStartDate);
                parameters2.put("remark", MapUtils.getString(map,"RepairsMsgOrther",""));
                parameters2.put("type","");
                try {
                    CRMApiUtils.getCRMServiceApi().syncWorkOrderAffirm(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),parameters2);
                } catch (Exception e) {
                    log.error("同步工单报修确认信息至CRM失败!错误信息:" + e.getMessage(),e);
                }
            }else if(type == 2){   //诊断结果信息
                //2.2.16 APP系统同步诊断结果确认信息到CCSS系统
                parameters2.put("faultSymptom",MapUtils.getString(map,"AffirmFaultSymptom",""));
                parameters2.put("diagnosisStepsAndResults",MapUtils.getString(map,"DiagnoseStepResult",""));
                parameters2.put("insureResponsibility",MapUtils.getString(map,"ConfirmDutyValue",""));
                parameters2.put("isStartRepair",MapUtils.getIntValue(map,"IsBeginRepair"));
                //拼装传给crm的零件集合
                List<Map<String,Object>> partInfoTS = new ArrayList<>();
                String partInfo = MapUtils.getString(map,"PartInfo","");
                String faultCodeInfo = MapUtils.getString(map,"FaultCodeInfos","");
                if(StringUtils.isNotEmpty(partInfo)){  //零件信息不为空
                    String[] partInfoIds = partInfo.split(",");
                    Map<String,Object> partInfoTMap = new HashMap<>();
                    for(String partInfoId : partInfoIds){
                        partInfoTMap = partInfoTDao.getPartInfoTById(Long.parseLong(partInfoId));
                        if(MapUtils.isNotEmpty(partInfoTMap)){
                            partInfoTMap.put("partNo",MapUtils.getString(partInfoTMap,"PartNumber",""));
                            partInfoTMap.put("partName",MapUtils.getString(partInfoTMap,"PartName",""));
                            partInfoTS.add(partInfoTMap);
                        }

                    }
                    if(CollectionUtils.isNotEmpty(partInfoTS)){
                        if(StringUtils.isNotEmpty(faultCodeInfo)){
                            String[] faultCodeInfos = faultCodeInfo.split(",");
                            int index = 0;
                            for(Map<String,Object> partInfoMap : partInfoTS){
                                if(index < faultCodeInfos.length){
                                    if(StringUtils.isNotEmpty(faultCodeInfos[index])){
                                        partInfoMap.put("faultCode",faultCodeInfos[index]);
                                    }else{
                                        partInfoMap.put("faultCode","");
                                    }
                                    index++;
                                }else{
                                    partInfoMap.put("faultCode","");
                                }
                            }
                        }else{
                            for(Map<String,Object> partInfoMap : partInfoTS){
                                partInfoMap.put("faultCode","");
                            }
                        }
                    }
                }
                parameters2.put("partsList",partInfoTS);
                try {
                    CRMApiUtils.getCRMServiceApi().syncConfirmationRepair(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),parameters2);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("同步工单诊断结果信息至CRM失败!错误信息:" + e.getMessage(),e);
                }
            }else if(type == 3){   //故障排查信息
                if(!map.containsKey("FaultExcludeStepResult")) {
                    obj.put("data", "");
                    obj.put("status", 1);
                    obj.put("msg", "故障排查信息不能为空!");
                    ParameterTool.writeResponse(response, obj.toString());
                    return null;
                }
                parameters2.put("diagnosisStepsAndResults",MapUtils.getString(map,"DiagnoseStepResult",""));
                parameters2.put("defaultEliminateDes",MapUtils.getString(map,"FaultExcludeStepResult",""));
                try {
                    CRMApiUtils.getCRMServiceApi().syncTroubleshootingSummary(companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo(),parameters2);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("同步工单故障排除信息至CRM失败!错误信息:" + e.getMessage(),e);
                }
            }else{
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "未知操作类型!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            map.put("ID",MapUtils.getLongValue(map,"CCECDiagnoseRepairMsId"));
            map.put("Updator",userT.getId());
            map.put("UpdateTime",currentTime);
            int updateNum = ccecDiagnoseRepairMsgTDao.updateByPrimaryKeySelective(map);
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
			return null;
        }catch (Exception e){
            ParameterTool.writeErrorResponse(response);
            //主动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage(), e);
        }
        return null;
    }


}
